package evi.com.evi.login;

import java.io.IOException;
import java.util.Map;
import java.util.regex.Pattern;

import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

import evi.com.evi.R;
import evi.com.evi.application.MyApplication;
import evi.com.evi.utils.AppUtils;
import evi.com.evi.utils.ConnectUtil;
import evi.com.evi.utils.ContentUtils;
import evi.com.evi.utils.JSONUtils;
import evi.com.evi.utils.RSAPublicUtil;
import evi.com.evi.utils.RegexUtils;
import evi.com.evi.utils.SPUtil;
import evi.com.evi.utils.SPUtils;
import evi.com.evi.utils.ScreenUtils;
import evi.com.evi.utils.ToastUtils;
import evi.com.evi.view.TimeButton;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ForgetPwdActivity extends Activity implements
        OnClickListener {

    private static final String TAG = "TAG";
    private View view;
    private boolean SEND = false;

    private TextView tv_title;

    private EditText et_phone;
    private EditText et_vali;
    private EditText et_pwd;
    private EditText et_pwd_isSure_;
    private View ll01;
    private View ll02;
    private TimeButton timeButton;
    private TextView tv_sure;

    private OkHttpClient client;
    private JSONUtils jsonUtil;

    private Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScreenUtils.setTranStatus(this, false, Color.parseColor("#FF6600"));
        MyApplication.getInstance().addActivity(this);
        view = View.inflate(this, R.layout.activity_forgetpwd, null);
        setContentView(view);

        initView();
        timeButton.setTextDes("获取验证码").setTextTime(60 * 1000).continueStatue();
        timeButton.setOnClickListener(this);
        initData();
    }

    private void initView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_vali = (EditText) findViewById(R.id.et_vali);
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        et_pwd_isSure_ = (EditText) findViewById(R.id.et_pwd_isSure_);

        ll01 = findViewById(R.id.ll01);
        ll02 = findViewById(R.id.ll02);

        timeButton = (TimeButton) view.findViewById(R.id.timeBt);
        tv_sure = (TextView) view.findViewById(R.id.tv_sure);

        client = new OkHttpClient();

        jsonUtil = new JSONUtils();
    }

    private void initData() {
        view.findViewById(R.id.forget_bar_back_left).setOnClickListener(this);
        timeButton.setOnClickListener(this);
        tv_sure.setOnClickListener(this);

        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (RegexUtils.isRegex(et_phone.getText().toString(),
                        RegexUtils.RX_Mobile)
                        && !TextUtils.isEmpty(et_phone.getText().toString())) {
                    SEND = true;
                } else {
                    SEND = false;
                }
            }
        });
    }

    private String phoneNo;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.forget_bar_back_left:
                finish();
                break;
            case R.id.timeBt:
                if (SEND) {
                    phoneNo = et_phone.getText().toString();
                    requestVerifyCode(phoneNo);
                } else {
                    timeButton.initStatue();
                    ToastUtils.showMsg(ForgetPwdActivity.this, "手机格式不对,请重新输入");
                }
                break;
            case R.id.tv_sure:// 确定
                String phone = et_phone.getText().toString();
                String smsCode = et_vali.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.showMsg(ForgetPwdActivity.this, "请输入手机号码");
                    return;
                } else if (!SEND) {
                    ToastUtils.showMsg(ForgetPwdActivity.this, "手机格式不对,请重新输入");
                    return;
                } else if (TextUtils.isEmpty(smsCode)) {
                    ToastUtils.showMsg(ForgetPwdActivity.this, "请输入验证码");
                    return;
                }
//			if (ll01.getVisibility() != View.GONE) {
//				ll02.setVisibility(View.VISIBLE);
//				ll01.setVisibility(View.GONE);
//				tv_title.setText("设置新密码");
//				tv_sure.setText("确定修改密码");
//				return;
//			}
                boolean flag_1 = TextUtils.isEmpty(et_phone.getText().toString());
                boolean flag_2 = TextUtils.isEmpty(et_vali.getText().toString());
                boolean flag_3 = TextUtils.isEmpty(et_pwd.getText().toString());
                boolean flag_4 = TextUtils.isEmpty(et_pwd_isSure_.getText()
                        .toString());

                if (flag_1 && flag_2 && flag_3 && flag_4) {
                    ToastUtils.showMsg(ForgetPwdActivity.this, "请填写完整信息");
                } else if (!et_pwd.getText().toString()
                        .equals(et_pwd_isSure_.getText().toString())) {
                    ToastUtils.showMsg(ForgetPwdActivity.this, "两次密码输入不一致");
                } else if (hasSpecialChar(et_pwd.getText().toString())
                        || !RegexUtils.isRegex(et_pwd.getText().toString(),
                        RegexUtils.RX_PWD)) {
                    ToastUtils.showMsg(ForgetPwdActivity.this, "密码由6-20位数字和字母组成");
                } else {
                    //此处找回密码
                    getRSA();
                }
                break;
        }
    }

    /**
     * 确定重置
     */
    private void confirm() {
        String code = et_vali.getText().toString();
        String password = et_pwd.getText().toString();
        String newPassword = RSAPublicUtil.publicEncryptString(modulus, exponent, code + password);
        String change = "?code=" + code + "&phoneNo=" + phoneNo + "&newPassword=" + newPassword;

        if (token == null) {
            token = "aaa";
        }

        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtils.message_change_url + change)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                toast("网络信号不佳，加载失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(ConnectUtil.isConnect(ForgetPwdActivity.this)){
                            toast("网络信号不佳，加载失败");
                        } else {
                            toast("网络未联接，请检查");
                        }
                    }
                });
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String dataMessage = response.body().string();

                if (jsonUtil.validate(dataMessage)) {
                    com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(dataMessage);
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Intent intent = new Intent(ForgetPwdActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                dismiss();
            }
        });

    }

    private String modulus;
    private String exponent;

    private void getRSA() {
        dialog = AppUtils.getLoadingDialog(this, "提示", "正在连接服务器，请稍后");
        dialog.show();
        Request request = new Request.Builder()
                .url(ContentUtils.RSA_url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                toast("网络信号不佳，加载失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(ConnectUtil.isConnect(ForgetPwdActivity.this)){
                            toast("网络信号不佳，加载失败");
                        } else {
                            toast("网络未联接，请检查");
                        }
                    }
                });
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        modulus = jsonObject.getJSONObject("data").getString("modulus");
                        exponent = jsonObject.getJSONObject("data").getString("exponent");
                        confirm();
                    } else {
                        toast(jsonObject.getString("message"));
                        dismiss();
                    }
                }

                Log.e(TAG, "RSA登录联网成功" + jsonData);
            }


        });
    }

    private String token;

    //获取验证码信息，进行验证码请求
    private void requestVerifyCode(String phoneNo) {
        dialog = AppUtils.getLoadingDialog(this, "提示", "正在获取验证码，请稍后");
        dialog.show();
        String message = "?phoneNo=" + phoneNo;
        Request request = new Request.Builder()
                .url(ContentUtils.message_url + message)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                toast("网络信号不佳，加载失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(ConnectUtil.isConnect(ForgetPwdActivity.this)){
                            toast("网络信号不佳，加载失败");
                        } else {
                            toast("网络未联接，请检查");
                        }
                    }
                });
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String dataMessage = response.body().string();
                if (jsonUtil.validate(dataMessage)) {
                    Log.e("TAG", dataMessage);
                    com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(dataMessage);
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        token = jsonObject.getJSONObject("data").getString("token");
                        SPUtil.setString(ForgetPwdActivity.this, "token", token);

                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                dismiss();
            }
        });
    }

    /**
     * 是否有特殊字符
     *
     * @param password
     * @return
     */
    public static boolean hasSpecialChar(String password) {
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        return Pattern.compile(regEx).matcher(password).find();
    }

    private void toast(final String string) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ForgetPwdActivity.this, string, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void dismiss() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getInstance().deleteActivity(this);
    }
}
